package com.thread;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.file.LocalFileCopy;
import com.util.MathHelper;

public class HandlerThread implements Runnable{
	
	private static Logger logger = Logger.getLogger(HandlerThread.class);
	
	private Socket socket;   
	private DataInputStream input = null;// 读取客户端数据    
	private DataOutputStream out = null; //向客户端发送数据
	private FileOutputStream fos;

	public HandlerThread(Socket client) {    
        socket = client;    
        new Thread(this).start();    
    }    

    public void run() {    
        try {    
            // 读取客户端数据    
        	input = new DataInputStream(socket.getInputStream());  
//            String clientInputStr = input.readUTF();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException  
            //处理客户端数据    
//            System.out.println("客户端发过来的内容:" + clientInputStr);    
            boolean status = this.disposeClientData(input);
            
            // 向客户端回复信息    
            out = new DataOutputStream(socket.getOutputStream());    
//            System.out.print("请输入:\t");    
//            // 发送键盘输入的一行    
//            String s = new BufferedReader(new InputStreamReader(System.in)).readLine();    
//            out.writeUTF("文件接收结束!"+status);
            logger.info("【接收文件】完成!客户端即将断开连接...");
            out.writeUTF("OK");
            
            out.close();    
            input.close();    
        } catch (Exception e) {
            //System.out.println("服务器 run 异常: " + e.getMessage());
            logger.info("【服务器】客户端已断开!ip"+socket.getInetAddress());
            logger.error("服务器 run 异常: " + e.getMessage());
        } finally {
            if (socket != null) {    
                try {    
                    socket.close();    
                } catch (Exception e) {    
                    socket = null;    
                    //System.out.println("服务端 finally 异常:" + e.getMessage()); 
                    logger.error("服务端 finally 异常:" + e.getMessage()); 
                }    
            }    
        }   
    }
    
    /**
     * 处理客户端数据
     */
    public boolean disposeClientData(DataInputStream dis) {
    	try {
    		//接收进度
    		double schedule = 0.0;
    		long startMili=System.currentTimeMillis();// 当前时间对应的毫秒数
    		long startMiliOnce = startMili;//
	    	//文件名和长度
	        String fileName = dis.readUTF();
	        String filePath = dis.readUTF();
	        long fileLength = dis.readLong();
//	        System.out.println("----开始接收文件<" + fileName + ">,文件大小为<" + fileLength + ">----");
	        logger.info("【接收文件】开始!"+fileName+",大小:"+fileLength+",位置:"+filePath);
            File path=new File(filePath);
            if (!path.exists()) {
                path.mkdirs();
            }
	        fos = new FileOutputStream(new File(filePath + fileName));
	        byte[] sendBytes = new byte[1024];
	        int transLen = 0;
	        while(transLen<fileLength){
                int read = 0;
                read = dis.read(sendBytes);
                if(read == -1){
                	break;
                }
                transLen += read;
                fos.write(sendBytes, 0, read);
                fos.flush();
                //进度
                double scheduleNow = MathHelper.div(transLen, fileLength, 2);
                scheduleNow = MathHelper.mul(scheduleNow,100);
                if(scheduleNow!=schedule){
                	schedule = scheduleNow;
                	double speed = MathHelper.div((fileLength-transLen),(System.currentTimeMillis()-startMiliOnce),0);
                	logger.info("【接收文件】进度"+ (int)schedule + "%!速度:"+speed+"kb/s");
                	startMiliOnce = System.currentTimeMillis();
                }
            }
            logger.info("【接收文件】 成功!耗时:"+(System.currentTimeMillis()-startMili)+"ms!"+filePath+fileName);
            fos.close(); 
            
            return true;
    	} catch (Exception e) {    
            System.out.println("处理客户端数据异常: " + e.getMessage());    
            return false;
        } finally {    
        	
        }
    	
    }
    
    
    public static void main(String[] args) {
    	double v1 = 8100935;
    	double v2 = 65467720;
    	MathHelper.div(v1, v2, 4);
    	
		System.out.println(MathHelper.div(v1, v2, 2));
	}
}
